<template>
  <div class="translation-container" :data-theme="theme">
    <div class="header">
      <h1>Translation</h1>
      <!-- <div class="theme-switcher">
        <button class="theme-btn" :class="{ active: theme === 'light' }" @click="setTheme('light')">
          浅色
        </button>
        <button class="theme-btn" :class="{ active: theme === 'dark' }" @click="setTheme('dark')">
          深色
        </button>
      </div> -->
    </div>

    <div class="source-section">
      <div class="section-header">
        <h2>原文</h2>
        <div class="actions">
          <button class="action-btn paste-btn" @click="pasteFromClipboard" :disabled="isPasting">
            <span v-if="isPasting">正在粘贴...</span>
            <span v-else>从剪贴板粘贴</span>
          </button>
          <button class="action-btn clear-btn" @click="clearSource">
            清空
          </button>
        </div>
      </div>

      <textarea v-model="sourceText" class="source-textarea" placeholder="请粘贴或输入要翻译的文本" @input="handleInput"></textarea>

      <div class="language-controls">
        <select v-model="sourceLanguage" class="language-select">
          <option v-for="lang in languages" :key="lang.code" :value="lang.code">
            {{ lang.name }}
          </option>
        </select>

        <button class="swap-btn" @click="swapLanguages">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="17 1 21 5 17 9"></polyline>
            <path d="M3 11V9a4 4 0 0 1 4-4h14"></path>
            <polyline points="7 23 3 19 7 15"></polyline>
            <path d="M21 13v2a4 4 0 0 1-4 4H3"></path>
          </svg>
        </button>
      </div>
    </div>

    <div class="target-section">
      <div class="section-header">
        <h2>译文</h2>
        <div class="actions">
          <button class="action-btn copy-btn" @click="copyTranslation" :disabled="!translatedText">
            复制译文
          </button>
          <button class="action-btn speak-btn" @click="speakTranslation" :disabled="!translatedText">
            朗读
          </button>
        </div>
      </div>

      <div class="translation-result" v-html="renderedTranslation"></div>

      <div class="language-controls">
        <select v-model="targetLanguage" class="language-select">
          <option v-for="lang in languages" :key="lang.code" :value="lang.code">
            {{ lang.name }}
          </option>
        </select>
      </div>
    </div>

    <div class="footer-controls">
      <label class="control-checkbox">
        <input type="checkbox" v-model="autoTranslate">
        <span>自动翻译</span>
      </label>

      <label class="control-checkbox">
        <input type="checkbox" v-model="monitorClipboard">
        <span>监控剪贴板</span>
      </label>

      <span class="char-count">字符数: {{ sourceText.length }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, inject, watch } from "vue";
import { marked } from "marked";
import { translateTextFunction } from "../api/gitTranslation.js"
// 使用注入的主题管理
const theme = inject("theme");
const setTheme = inject("setTheme");

// 数据状态
const sourceText = ref("");
const translatedText = ref("");
const isPasting = ref(false);
const isTranslating = ref(false);
const autoTranslate = ref(true);
const monitorClipboard = ref(false);
const lastClipboardText = ref("");

// 语言选择
const sourceLanguage = ref("auto");
const targetLanguage = ref("zh-CN");
const languages = ref([
  { code: "auto", name: "自动检测" },
  { code: "zh-CN", name: "中文" },
  { code: "en", name: "英语" },
  { code: "sq", name: "阿尔巴尼亚语" },
  { code: "ar", name: "阿拉伯语" },
  { code: "am", name: "阿姆哈拉语" },
  { code: "as", name: "阿萨姆语" },
  { code: "az", name: "阿塞拜疆语" },
  { code: "ee", name: "埃维语" },
  { code: "ay", name: "艾马拉语" },
  { code: "ga", name: "爱尔兰语" },
  { code: "et", name: "爱沙尼亚语" },
  { code: "or", name: "奥利亚语" },
  { code: "om", name: "奥罗莫语" },
  { code: "eu", name: "巴斯克语" },
  { code: "be", name: "白俄罗斯语" },
  { code: "bm", name: "班巴拉语" },
  { code: "bg", name: "保加利亚语" },
  { code: "is", name: "冰岛语" },
  { code: "pl", name: "波兰语" },
  { code: "bs", name: "波斯尼亚语" },
  { code: "fa", name: "波斯语" },
  { code: "bho", name: "博杰普尔语" },
  { code: "af", name: "布尔语(南非荷兰语)" },
  { code: "tt", name: "鞑靼语" },
  { code: "da", name: "丹麦语" },
  { code: "de", name: "德语" },
  { code: "dv", name: "迪维希语" },
  { code: "ti", name: "蒂格尼亚语" },
  { code: "doi", name: "多格来语" },
  { code: "ru", name: "俄语" },
  { code: "fr", name: "法语" },
  { code: "sa", name: "梵语" },
  { code: "tl", name: "菲律宾语" },
  { code: "fi", name: "芬兰语" },
  { code: "fy", name: "弗里西语" },
  { code: "km", name: "高棉语" },
  { code: "ka", name: "格鲁吉亚语" },
  { code: "gom", name: "贡根语" },
  { code: "gu", name: "古吉拉特语" },
  { code: "gn", name: "瓜拉尼语" },
  { code: "kk", name: "哈萨克语" },
  { code: "ht", name: "海地克里奥尔语" },
  { code: "ko", name: "韩语" },
  { code: "ha", name: "豪萨语" },
  { code: "nl", name: "荷兰语" },
  { code: "ky", name: "吉尔吉斯语" },
  { code: "gl", name: "加利西亚语" },
  { code: "ca", name: "加泰罗尼亚语" },
  { code: "cs", name: "捷克语" },
  { code: "kn", name: "卡纳达语" },
  { code: "co", name: "科西嘉语" },
  { code: "kri", name: "克里奥尔语" },
  { code: "hr", name: "克罗地亚语" },
  { code: "qu", name: "克丘亚语" },
  { code: "ku", name: "库尔德语（库尔曼吉语）" },
  { code: "ckb", name: "库尔德语（索拉尼）" },
  { code: "la", name: "拉丁语" },
  { code: "lv", name: "拉脱维亚语" },
  { code: "lo", name: "老挝语" },
  { code: "lt", name: "立陶宛语" },
  { code: "ln", name: "林格拉语" },
  { code: "lg", name: "卢干达语" },
  { code: "lb", name: "卢森堡语" },
  { code: "rw", name: "卢旺达语" },
  { code: "ro", name: "罗马尼亚语" },
  { code: "mg", name: "马尔加什语" },
  { code: "mt", name: "马耳他语" },
  { code: "mr", name: "马拉地语" },
  { code: "ml", name: "马拉雅拉姆语" },
  { code: "ms", name: "马来语" },
  { code: "mk", name: "马其顿语" },
  { code: "mai", name: "迈蒂利语" },
  { code: "mi", name: "毛利语" },
  { code: "mni-Mtei", name: "梅泰语（曼尼普尔语）" },
  { code: "mn", name: "蒙古语" },
  { code: "bn", name: "孟加拉语" },
  { code: "lus", name: "米佐语" },
  { code: "my", name: "缅甸语" },
  { code: "hmn", name: "苗语" },
  { code: "xh", name: "南非科萨语" },
  { code: "zu", name: "南非祖鲁语" },
  { code: "ne", name: "尼泊尔语" },
  { code: "no", name: "挪威语" },
  { code: "pa", name: "旁遮普语" },
  { code: "pt", name: "葡萄牙语" },
  { code: "ps", name: "普什图语" },
  { code: "ny", name: "齐切瓦语" },
  { code: "ak", name: "契维语" },
  { code: "ja", name: "日语" },
  { code: "sv", name: "瑞典语" },
  { code: "sm", name: "萨摩亚语" },
  { code: "sr", name: "塞尔维亚语" },
  { code: "nso", name: "塞佩蒂语" },
  { code: "st", name: "塞索托语" },
  { code: "si", name: "僧伽罗语" },
  { code: "eo", name: "世界语" },
  { code: "sk", name: "斯洛伐克语" },
  { code: "sl", name: "斯洛文尼亚语" },
  { code: "sw", name: "斯瓦希里语" },
  { code: "gd", name: "苏格兰盖尔语" },
  { code: "ceb", name: "宿务语" },
  { code: "so", name: "索马里语" },
  { code: "tg", name: "塔吉克语" },
  { code: "te", name: "泰卢固语" },
  { code: "ta", name: "泰米尔语" },
  { code: "th", name: "泰语" },
  { code: "tr", name: "土耳其语" },
  { code: "tk", name: "土库曼语" },
  { code: "cy", name: "威尔士语" },
  { code: "ug", name: "维吾尔语" },
  { code: "ur", name: "乌尔都语" },
  { code: "uk", name: "乌克兰语" },
  { code: "uz", name: "乌兹别克语" },
  { code: "es", name: "西班牙语" },
  { code: "iw", name: "希伯来语" },
  { code: "el", name: "希腊语" },
  { code: "haw", name: "夏威夷语" },
  { code: "sd", name: "信德语" },
  { code: "hu", name: "匈牙利语" },
  { code: "sn", name: "修纳语" },
  { code: "hy", name: "亚美尼亚语" },
  { code: "ig", name: "伊博语" },
  { code: "ilo", name: "伊洛卡诺语" },
  { code: "it", name: "意大利语" },
  { code: "yi", name: "意第绪语" },
  { code: "hi", name: "印地语" },
  { code: "su", name: "印尼巽他语" },
  { code: "id", name: "印尼语" },
  { code: "jw", name: "印尼爪哇语" },
  { code: "yo", name: "约鲁巴语" },
  { code: "vi", name: "越南语" },
  { code: "ts", name: "宗加语" }
]);


// 计算属性
const renderedTranslation = computed(() => {
  return marked(translatedText.value || "翻译结果将显示在这里...");
});

// 方法
const pasteFromClipboard = async () => {
  try {
    isPasting.value = true;
    const text = await navigator.clipboard.readText();
    sourceText.value = text;
    lastClipboardText.value = text;
    showMessage("已从剪贴板粘贴文本", "success");

    if (autoTranslate.value) {
      translateText();
    }
  } catch (error) {
    showMessage("无法访问剪贴板: " + error.message, "error");
  } finally {
    isPasting.value = false;
  }
};

const clearSource = () => {
  sourceText.value = "";
  translatedText.value = "";
};

const swapLanguages = () => {
  const temp = sourceLanguage.value;
  sourceLanguage.value = targetLanguage.value;
  targetLanguage.value = temp;

  if (sourceText.value && translatedText.value) {
    const tempText = sourceText.value;
    sourceText.value = translatedText.value;
    translatedText.value = tempText;
  } else if (translatedText.value) {
    sourceText.value = translatedText.value;
    translatedText.value = "";
  }
};

const copyTranslation = async () => {
  try {
    await navigator.clipboard.writeText(translatedText.value);
    showMessage("译文已复制到剪贴板", "success");
  } catch (error) {
    showMessage("复制失败: " + error.message, "error");
  }
};

const speakTranslation = () => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(translatedText.value);
    utterance.lang = targetLanguage.value;
    speechSynthesis.speak(utterance);
  } else {
    showMessage("您的浏览器不支持文本朗读功能", "warning");
  }
};

const translateText = async () => {
  if (!sourceText.value.trim()) {
    translatedText.value = "";
    return;
  }

  if (sourceLanguage.value === targetLanguage.value) {
    translatedText.value = sourceText.value;
    return;
  }

  try {
    isTranslating.value = true;

    // 调用真实 API 获取翻译结果
    const result = await translateTextFunction(
      sourceText.value,
      sourceLanguage.value,
      targetLanguage.value
    );

    translatedText.value = result;
  } catch (error) {
    showMessage("翻译失败: " + error.message, "error");
  } finally {
    isTranslating.value = false;
  }
};

const handleInput = () => {
  if (autoTranslate.value) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(translateText, 500);
  }
};

const showMessage = (text, type) => {
  const message = document.createElement("div");
  message.className = `message ${type}`;
  message.textContent = text;
  document.body.appendChild(message);

  setTimeout(() => {
    message.classList.add("show");
  }, 10);

  setTimeout(() => {
    message.classList.remove("show");
    setTimeout(() => {
      document.body.removeChild(message);
    }, 300);
  }, 3000);
};

let debounceTimer = null;
let clipboardInterval = null;

// 监控剪贴板变化
const checkClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText();
    if (text && text !== lastClipboardText.value && text !== sourceText.value) {
      lastClipboardText.value = text;
      sourceText.value = text;
      showMessage("检测到剪贴板新内容，已自动加载", "info");

      if (autoTranslate.value) {
        translateText();
      }
    }
  } catch (error) {
    console.error("无法读取剪贴板:", error);
  }
};

// 生命周期钩子
onMounted(() => {
  if (monitorClipboard.value) {
    clipboardInterval = setInterval(checkClipboard, 2000);
  }
});

onUnmounted(() => {
  if (clipboardInterval) {
    clearInterval(clipboardInterval);
  }
});

// 监听监控剪贴板选项变化
watch(monitorClipboard, (newVal) => {
  if (newVal) {
    clipboardInterval = setInterval(checkClipboard, 2000);
  } else {
    clearInterval(clipboardInterval);
    clipboardInterval = null;
  }
});
</script>

<style scoped>
.translation-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  padding: 20px;
  /* background-color: var(--bg-color-diff); */
  transition: all 0.3s ease;
  border-radius: 10px;
  border: 1px solid var(--border-color);
  box-shadow: 0 0px 10px 3px var(--shadow-color);
}

/* [data-theme="light"] {
  --bg-color: #ffffff;
  --btn-text: #222222;
  --btn-bg: #f0f0f0;
  --bg-color-change1: #dffff3;
  --bg-color-change2: #e9d9ff;
  --bg-color-change3: #f9ffdd;
  --bg-color-deg: 270deg;
  --bg-color-flag: #f7f7f7;
  --border-color: #9a9da1;
  --bg-color-diff: #f3f4f6;
  --primary-color: #4a6bff;
  --correct-color: #4caf50;
  --wrong-color: #f44336;
  --text-color: #2d3748;
  --text-color-flag: #222a38;
  --card-bg: #ffffff;
  --shadow-color: rgba(0, 0, 0, 0.1);
  --hint-color: #6b7280;
  --progress-color: var(--primary-color);
  --search-bg: #1e3c72;
  --save-btn-color: #e3f2fd;
  --practice-btn-color: #e8f5e9;
}

[data-theme="dark"] {
  --bg-color: #1a1a1a;
  --btn-text: #ffffff;
  --btn-bg: #333333;
  --bg-color-change1: #003322;
  --bg-color-change2: #220044;
  --bg-color-change3: #443300;
  --bg-color-deg: 270deg;
  --bg-color-flag: #333333;
  --border-color: #555555;
  --bg-color-diff: #242424;
  --primary-color: #5d7dff;
  --correct-color: #4caf50;
  --wrong-color: #f44336;
  --text-color: #e5e5e5;
  --text-color-flag: #ffffff;
  --card-bg: #242424;
  --shadow-color: rgba(0, 0, 0, 0.3);
  --hint-color: #a0a0a0;
  --progress-color: var(--primary-color);
  --search-bg: #1e3c72;
  --save-btn-color: #1e3c72;
  --practice-btn-color: #2e4d2e;
} */

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color);
}

.header h1 {
  margin: 0;
  color: var(--text-color);
  font-size: 1.5rem;
}

.theme-switcher {
  display: flex;
  gap: 8px;
}

.theme-btn {
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  background-color: var(--btn-bg);
  color: var(--btn-text);
  cursor: pointer;
  transition: all 0.2s;
}

.theme-btn.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.source-section,
.target-section {
  margin-bottom: 20px;
  background-color: var(--card-bg);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px var(--shadow-color);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: var(--text-color);
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  background-color: var(--btn-bg);
  color: var(--btn-text);
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.9rem;
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.paste-btn {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.copy-btn {
  background-color: var(--save-btn-color);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.speak-btn {
  background-color: var(--practice-btn-color);
  border-color: var(--correct-color);
  color: var(--correct-color);
}

.clear-btn {
  background-color: var(--bg-color-diff);
}

.source-textarea {
  width: 95%;
  min-height: 150px;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  background-color: var(--bg-color);
  color: var(--text-color);
  font-size: 1rem;
  resize: vertical;
  margin-bottom: 12px;
}

.translation-result {
  width: 95%;
  max-height: 100px;
  /* 新增：设置最大高度 */
  min-height: 150px;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  background-color: var(--bg-color);
  color: var(--text-color);
  font-size: 1rem;
  margin-bottom: 12px;
  overflow-y: auto;
  /* 自动显示滚动条 */
}

.language-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.language-select {
  flex: 1;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  background-color: var(--bg-color);
  color: var(--text-color);
  font-size: 0.9rem;
}

.swap-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 1px solid var(--border-color);
  background-color: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.swap-btn:hover {
  background-color: var(--bg-color-diff);
}

.footer-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 12px 0;
  border-top: 1px solid var(--border-color);
}

.control-checkbox {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--text-color);
  font-size: 0.9rem;
}

.control-checkbox input {
  width: 16px;
  height: 16px;
}

.char-count {
  margin-left: auto;
  color: var(--hint-color);
  font-size: 0.9rem;
}

/* 消息提示样式 */
.message {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(100%);
  padding: 12px 20px;
  border-radius: 4px;
  color: white;
  opacity: 0;
  transition: all 0.3s ease;
  z-index: 1000;
}

.message.show {
  transform: translateX(-50%) translateY(0);
  opacity: 1;
}

.message.success {
  background-color: var(--correct-color);
}

.message.error {
  background-color: var(--wrong-color);
}

.message.warning {
  background-color: #ff9800;
}

.message.info {
  background-color: var(--primary-color);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .theme-switcher {
    align-self: flex-end;
  }

  .footer-controls {
    flex-wrap: wrap;
    gap: 12px;
  }

  .char-count {
    margin-left: 0;
    width: 100%;
  }
}
</style>